<template>
  <view class="friend-selector">
    <!-- 选择按钮 -->
    <button 
      class="select-friend-btn" 
      @click="showFriendList"
      :disabled="disabled"
    >
      <text v-if="selectedFriend">
        {{ selectedFriend.nickname || selectedFriend.friendNickname || '未知用户' }}
      </text>
      <text v-else>{{ props.mode === 'team' ? '选择队员' : '选择好友' }}</text>
    </button>

    <!-- 好友列表弹窗 -->
    <view v-if="showList" class="friend-list-modal">
      <view class="modal-header">
        <text class="modal-title">{{ props.mode === 'team' ? '选择队员' : '选择好友' }}</text>
        <button class="close-btn" @click="closeModal">×</button>
      </view>
      
      <!-- 搜索框 -->
      <view class="search-container">
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          :placeholder="props.mode === 'team' ? '搜索队员...' : '搜索好友...'"
          @input="onSearch"
        />
      </view>
      
      <!-- 好友列表 -->
      <scroll-view class="friend-list" scroll-y>
        <view v-if="loading" class="loading">
          <text>加载中...</text>
        </view>
        
        <view v-else-if="filteredFriends.length" class="friends-container">
          <view 
            v-for="friend in filteredFriends" 
            :key="friend.id" 
            class="friend-item"
            @click="selectFriend(friend)"
          >
            <image 
              :src="getAvatarUrl(friend.avatarUrl || friend.friendAvatarUrl)" 
              class="friend-avatar" 
              @error="handleAvatarError" 
            />
            <view class="friend-info">
              <text class="friend-name">{{ friend.nickname || friend.friendNickname }}</text>
              <text class="friend-status" :class="{ online: friend.isOnline }">
                {{ friend.isOnline ? '在线' : '离线' }}
              </text>
            </view>
            <view v-if="selectedFriend && selectedFriend.friendId === friend.friendId" class="selected-indicator">
              ✓
            </view>
          </view>
        </view>
        
        <view v-else class="empty-state">
          <text class="empty-text">{{ props.mode === 'team' ? '暂无队员' : '暂无好友' }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getAvatarUrl } from '@/utils/imageUtils.js'

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  currentUserId: {
    type: [String, Number],
    required: true
  },
  mode: {
    type: String,
    default: 'friends', // 'friends' 或 'team'
    validator: (value) => ['friends', 'team'].includes(value)
  },
  teamMembers: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['select', 'clear'])

// 数据
const showList = ref(false)
const friends = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const selectedFriend = ref(null)

// 计算属性
const filteredFriends = computed(() => {
  if (!searchKeyword.value) return friends.value
  
  return friends.value.filter(friend => {
    const name = friend.nickname || friend.friendNickname || ''
    return name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  })
})

// 方法
const showFriendList = () => {
  if (props.disabled) return
  showList.value = true
  loadFriends()
}

const closeModal = () => {
  showList.value = false
  searchKeyword.value = ''
}

const selectFriend = (friend) => {
  selectedFriend.value = friend
  emit('select', friend)
  closeModal()
}

const clearSelection = () => {
  selectedFriend.value = null
  emit('clear')
}

const loadFriends = async () => {
  loading.value = true
  try {
    if (props.mode === 'team') {
      // 队员模式：直接使用传入的团队成员数据
      friends.value = props.teamMembers || []
    } else {
      // 好友模式：从API获取好友列表
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/friends',
        method: 'GET',
        header: {
          'Access-Token': `Bearer ${token}`
        }
      })

      if (response.data && response.data.code === 200) {
        // 过滤掉自己
        friends.value = (response.data.data || []).filter(friend => 
          friend.friendId && String(friend.friendId) !== String(props.currentUserId)
        )
      }
    }
  } catch (error) {
    console.error('加载列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

const onSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleAvatarError = (e) => {
  console.log('头像加载失败:', e)
}

// 暴露方法给父组件
defineExpose({
  clearSelection,
  setSelectedFriend: (friend) => {
    selectedFriend.value = friend
  }
})
</script>

<style scoped>
.friend-selector {
  position: relative;
}

.select-friend-btn {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: #fff;
  text-align: left;
  font-size: 14px;
  color: #333;
}

.select-friend-btn:disabled {
  background: #f5f5f5;
  color: #999;
}

.friend-list-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f5f5f5;
  border-radius: 50%;
  font-size: 20px;
  color: #666;
}

.search-container {
  padding: 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.search-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.friend-list {
  flex: 1;
  background: #fff;
}

.friends-container {
  padding: 0 16px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.friend-item:last-child {
  border-bottom: none;
}

.friend-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.friend-info {
  flex: 1;
}

.friend-name {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.friend-status {
  font-size: 12px;
  color: #999;
}

.friend-status.online {
  color: #4CAF50;
}

.selected-indicator {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #4CAF50;
  font-size: 18px;
  font-weight: bold;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.empty-text {
  color: #999;
  font-size: 14px;
}
</style>

